package blackhouse_dao;

import java.sql.CallableStatement;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import com.mysql.jdbc.Connection;

public class jdbc_dao
{
	public Connection	conn	= null;
	public Statement	st		= null;

	private Connection info()
	{

		try
		{
			Class.forName("com.mysql.jdbc.Driver");
			conn = (Connection) DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/t1831_project7", "root",
					"1234");
			return conn;
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 执行存储过程，进行数据分页
	 * 
	 * @throws SQLException
	 * **/
	public ResultSet execute_Proc_Page(String sql, List<Object> list,
			int[] countSize) throws SQLException
	{
		conn = info();
		CallableStatement cs = conn.prepareCall(sql);
		if (list != null)
		{
			for (int i = 0; i < list.size(); i++)
			{
				cs.setObject(i + 1, list.get(i));
			}
		}
		cs.registerOutParameter(4, java.sql.Types.INTEGER); // 设置输出参数
		ResultSet rs = cs.executeQuery();
		countSize[0] = cs.getInt(4);
		return rs;
	}

	public boolean execute_Proc(String sql, List<Object> list)
			throws SQLException
	{
		conn = info();
		PreparedStatement pres = conn.prepareCall(sql);
		if (list != null)
		{
			for (int i = 0; i < list.size(); i++)
			{
				pres.setObject(i + 1, list.get(i));
			}
		}
		return pres.execute();
	}

	public int update(String sql)
	{

		try
		{
			conn = info();
			st = conn.createStatement();
			return st.executeUpdate(sql);// 閺囧瓨鏌婇弫鐗堝祦鎼存挸鍤遍弫锟�
		} catch (SQLException e)
		{
			e.printStackTrace();
			return 0;
		} finally
		{
			close(conn, st, null);
		}
	}

	public ResultSet query(String sql)
	{

		try
		{
			conn = info();
			st = conn.createStatement();
			return st.executeQuery(sql);
		} catch (SQLException e)
		{
			e.printStackTrace();
			return null;
		}

	}

	public void close(Connection conn, Statement st, ResultSet rs)
	{
		try
		{
			if (rs != null)
				rs.close();
			if (st != null)
				st.close();
			if (conn != null)
				conn.close();
		} catch (Exception e)
		{
		}
	}
}
